package com.collectplus.express.self;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.text.Html;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.app.Animator;
import com.collectplus.express.app.AppCaptureActivity;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppConfig;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.menu.WebViewActivity;
import com.collectplus.express.model.BagBean;
import com.collectplus.express.model.Const;
import com.collectplus.express.model.ExpressCompanyBean;
import com.collectplus.express.model.ReceiverBean;
import com.collectplus.express.model.SelfPrePriceBean;
import com.collectplus.express.model.SenderBean;
import com.collectplus.express.model.ServicePointBean;
import com.collectplus.express.model.VisitGetCourierStateBean;
import com.collectplus.express.tools.SharedPref;
import com.collectplus.express.tools.TextWatcherExt;
import com.collectplus.express.view.LinearLayoutWithLine;
import com.collectplus.express.wxapi.Constants;
import com.shouhuobao.bhi.loc.BaiduLocationService;
import com.shouhuobao.bhi.login.LoginActivity;
import com.shouhuobao.bhi.receiver.ReceiverCameraActivity;
import com.shouhuobao.bhi.receiver.ReceiverTabFragmentActivity;
import com.shouhuobao.visit.VisitHomeActivity;

import java.text.MessageFormat;
import java.util.ArrayList;

import droid.frame.app.Callback;
import droid.frame.ui.utils.Utils;
import droid.frame.umeng.UMeng;
import droid.frame.utils.android.MathUtils;
import droid.frame.utils.http.BitmapUtils;
import droid.frame.utils.lang.Str;
import droid.frame.view.InputFilterExt;

/**
 * 6.9 自助寄件表单填写<br>
 * 主要包括收件人、包裹、物品类型、图片<br>
 *
 * @author coffee <br>
 * 2016-9-24下午1:43:19
 */
public class SelfFormInfoActivity extends BaseActivity2 implements OnClickListener {

    private TextView mBagCode;// 投递袋上的二维码  投递编号 有袋子编号显示为投递编号：111 111  没有袋子编号显示投递编号
    private TextView mBagName;//没有袋子编号显示  可通过火箭投递袋、面单获得   有袋子编号显示  火箭投递袋-小黄袋
    private TextView mChooseBagTV;//选填袋子
    private TextView mReceiverInfo;// 收件人信息
    private TextView mGoodsType;// 物品类型
    private ImageView mGoodsImage;// 包裹照片
    private TextView mExpressNameTV;//快递公司名称
    private TextView mRemark;// 备注
    private TextView mRemarkState;// 备注状态
    private LinearLayout mSubmit;// 提交

    private ReceiverBean cacheReceiver;
    private BagBean cacheBagBean;
    private TextView mSenderInfo;//寄件人
    private String remark;
    private LinearLayoutWithLine mAddSender;// 添加寄件人
    private TextView mReceiverDown;// 下拉抽屉按钮
    private TextView mPrePayMoneyTV;//预支付的金额
    private TextView mPrePayStampTV;//使用邮票提示
    private ViewGroup mPreLayout;//预支付布局
    private ViewGroup mBottomLayout;//底部布局
    private ViewGroup mExpressCompanyLayout = null;
    private PopupWindow popwin = null;
    private SelfPrePriceBean prePriceBean = null;
    private String prePayStr = "<font color=#404040>预计需支付</font><font color=#E91919>{0}</font><font color=#404040>元</font>";
    private String stampTipStr = "<font color=#404040>使用邮票低至</font><font color=#E91919>{0}</font><font color=#404040>元</font>";
    private String callCenterStr = "<font color=#181818>周边暂无可上门火箭侠，可</font><font color=#1990e2><u>联系客服</u></font><font color=#181818>人工调度</font>";
    private String centerNumStr = "<font color=#181818>周边有</font><font color=#F54951>{0}</font><font color=#181818>个火箭侠待命取件，请尽快下单预约上门</font>";
    private ArrayList<ExpressCompanyBean> mExpressCompanyList = null;

    private TextView mCourierLocationTV;
    private TextView mCourierNewLocationBtn;
    private BDLocation bdLocation = null;
    private VisitGetCourierStateBean courierResultItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 开始创建包裹
        cacheReceiver = AppCache.getParcelNew();
        if (cacheReceiver == null) {
            cacheReceiver = new ReceiverBean(1);
            AppCache.setParcelNew(cacheReceiver);
        } else {
            cacheReceiver.setType(1);// 自助寄件
        }
        cacheBagBean = (BagBean) getIntent().getSerializableExtra("bag");
        if (cacheBagBean == null) {
            cacheBagBean = cacheReceiver.getBag();
            if (cacheBagBean == null) {
                cacheBagBean = new BagBean();
                cacheReceiver.setBag(cacheBagBean);
            }
        } else {
            cacheReceiver.setBag(cacheBagBean);
        }
        super.onCreate(savedInstanceState);
        location();
        loadDataFromCache();
        if (SharedPref.isFirstOpen(Constants.isShowOrderTip)) {
            startActivity(SelfUserPassportActivity.class);
        }
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.self_form_info);
        super.findViewById();
        getAppTitle().setCommonTitle("填写包裹信息");
        mBagCode = (TextView) findViewById(R.id.self_bag_code);
        mReceiverInfo = (TextView) findViewById(R.id.self_receiver_info);
        mGoodsType = (TextView) findViewById(R.id.self_goods_type);
        mExpressNameTV = (TextView) findViewById(R.id.self_expresscompany_tv);
        mGoodsImage = (ImageView) findViewById(R.id.self_goods_image);
        // set onclick
        findViewById(R.id.self_receiver_layout).setOnClickListener(this);
        findViewById(R.id.self_goods_layout).setOnClickListener(this);
        mExpressCompanyLayout = (ViewGroup) findViewById(R.id.self_expresscompany_layout);
        mExpressCompanyLayout.setOnClickListener(this);
        mGoodsImage.setOnClickListener(this);
//        mSubmit = (Button) findViewById(R.id.self_next_action);
        mSubmit = (LinearLayout) findViewById(R.id.self_next_action);
        mSubmit.setOnClickListener(this);
        // 收件人的下拉
        findViewById(R.id.self_drawer_button_layout).setOnClickListener(this);
        mReceiverDown = (TextView) findViewById(R.id.receiver_down);
        // 添加寄件人的总布局
        mAddSender = (LinearLayoutWithLine) findViewById(R.id.self_send_info_layout);
        // 寄件人信息
        mSenderInfo = (TextView) findViewById(R.id.self_send_info);
        // 寄件人信息的总布局
        mAddSender.setOnClickListener(this);
        // 添加备注的布局
        findViewById(R.id.self_receiver_remark_layout).setOnClickListener(this);
        // set data
        mBagName = (TextView) findViewById(R.id.self_bag_name);
        mChooseBagTV = (TextView) findViewById(R.id.choose_bag_TV);
        mChooseBagTV.setOnClickListener(this);
        findViewById(R.id.choose_bagcode_ll).setOnClickListener(this);
        // 设置默认的寄件人姓名
//        UserBean user = AppCache.getUser();
//        if (user != null && isNotEmpty(user.getName())) {
//            mSenderInfo.setText("寄件人: " + user.getName());
//        }
        // 备注(选填、已添加)
        mRemark = (TextView) findViewById(R.id.receiver_remark);
        mRemarkState = (TextView) findViewById(R.id.receiver_remark_state);
        //预支付的金额
        mPreLayout = (ViewGroup) findViewById(R.id.pre_layout);
        mPrePayMoneyTV = (TextView) findViewById(R.id.pre_pay_money_tv);
        mPrePayStampTV = (TextView) findViewById(R.id.pre_pay_stamp_tv);
        mPreLayout.setVisibility(View.INVISIBLE);
        mBottomLayout = (ViewGroup) findViewById(R.id.bottom_layout);
        mBottomLayout.setVisibility(View.GONE);
        //打开或关闭popwin
        findViewById(R.id.open_or_close_pop_iv).setOnClickListener(this);
//        setButtonEnableStyle(mSubmit, false);
        setLinearLayoutEnableStyle(mSubmit, false);
        mReceiverInfo.addTextChangedListener(watcher);
        mGoodsType.addTextChangedListener(watcher);
        mExpressNameTV.addTextChangedListener(watcher);
        mReceiverInfo.setFilters(new InputFilter[]{new InputFilterExt(0)});
        mSenderInfo.setFilters(new InputFilter[]{new InputFilterExt(0)});
        //顶部显示火箭侠的状态
        mCourierLocationTV = (TextView) findViewById(R.id.courier_location_tv);
        mCourierLocationTV.setOnClickListener(this);
        mCourierNewLocationBtn = (TextView) findViewById(R.id.courier_new_location_tv);
        mCourierNewLocationBtn.setOnClickListener(this);
    }

    private void location() {
        showLoadingDialog("正在定位");
        Intent intent = new Intent();
        intent.setClass(getContext(), BaiduLocationService.class);
        intent.setPackage(getPackageName());
        intent.putExtra("msgId", MsgID.self_baidu_location);
        startService(intent);
    }

    private void loadDataFromCache() {
        // 从缓存中加载收件人
        String result = cacheReceiver.getName();
        // 注意先设置tag -- 因为setText以后会触发TextWatcher
        if (isNotEmpty(result)) {
            mReceiverInfo.setTag(result);
            mReceiverInfo.setText("收件人: " + result + " " + cacheReceiver.getPhone());
        }
        // 从缓存中加载图片
        String capturePath = cacheReceiver.getImageUrl();
        if (isNotEmpty(capturePath)) {
            setGoodsImage(capturePath);
        }
        // 物品类型
        if (cacheReceiver.getServicePoint() != null) {
            ServicePointBean item = cacheReceiver.getServicePoint();
            if (isNotEmpty(item.getGoodsType())) {
                mGoodsType.setText(item.getGoodsType() + " " + cacheReceiver.getWeight() + "kg");
            }
        }
        // 寄件人
        if (cacheReceiver.getSender() != null) {
            mSenderInfo.setTag(cacheReceiver.getSender().getName());
            mSenderInfo.setText("寄件人: " + cacheReceiver.getSender().getName() + " " + cacheReceiver.getSender().getPhone());
        } else {
            SenderBean senderBean = AppCache.getSenderBean();
            if (senderBean != null) {
                mSenderInfo.setTag(senderBean.getName());
                mSenderInfo.setText("寄件人: " + senderBean.getName() + " " + senderBean.getPhone());
                cacheReceiver.setSender(senderBean);
            }
        }
        cacheReceiver.setExpressCompanyId(null);
        cacheReceiver.setExpressCompanyName(null);
//        if (isNotEmpty(cacheReceiver.getExpressCompanyId()) && isNotEmpty(cacheReceiver.getExpressCompanyName())) {
//            mExpressNameTV.setTextColor(getResources().getColor(R.color.app_fontcolor_333333));
//            mExpressNameTV.setText(cacheReceiver.getExpressCompanyName());
//            mExpressNameTV.setTag(cacheReceiver.getExpressCompanyName());
//        } else {
//            mExpressNameTV.setTextColor(getResources().getColor(R.color.app_font_2));
//            mExpressNameTV.setTag(null);
//            mExpressNameTV.setText("必填");
//        }
        // 从缓存中加载备注
        remark = cacheReceiver.getRemark();
        setRemarkText(remark);
        BagBean bagBean = cacheReceiver.getBag();
        if (bagBean != null && isNotEmpty(bagBean.getCode())) {
            mBagCode.setText("投递编号：" + Str.strFormatByEmpty(bagBean.getCode(), true, 2, 3));
            mBagName.setText(bagBean.getName());
            mChooseBagTV.setText("");
        } else {
            mBagCode.setText("投递编号");
            mBagName.setText("可通过火箭投递袋、面单获得");
            mChooseBagTV.setText("选填");
        }
    }

    private TextWatcherExt watcher = new TextWatcherExt() {
        public void afterTextChanged(android.text.Editable s) {
            if (isNotEmpty(mReceiverInfo.getTag()) && isNotEmpty(cacheReceiver.getGoodsImage()) //
                    && isNotEmpty(mGoodsType.getText()) && isNotEmpty(cacheReceiver.getAddress())
                    && isNotEmpty(cacheReceiver.getPhone()) && isNotEmpty(cacheReceiver.getProvince()) && isNotEmpty(cacheReceiver.getWeight())) {
                mBottomLayout.setVisibility(View.VISIBLE);
                prePriceFunction();
            } else {
                mBottomLayout.setVisibility(View.GONE);
//                setButtonEnableStyle(mSubmit, false);
                setLinearLayoutEnableStyle(mSubmit, false);
            }
        }
    };

    /**
     * 价格预估
     */
    private void prePriceFunction() {
        if (mReceiverInfo.getTag() == null) {
            return;
        }
        //选择完成物品类型和重量后请求服务器的预支付金额
        showLoadingDialog(null);
        SenderBean senderBean = cacheReceiver.getSender();
        String city = "";
        if (senderBean == null || isEmpty(senderBean.getCity())) {
            if (isEmpty(AppCache.getCurrentCityName())) {
                AppCache.setCurrentCityName("北京市");
                city = "北京市";
            } else {
                city = AppCache.getCurrentCityName();
            }
        } else {
            city = senderBean.getCity();
        }
        //没有快递公司
        if (isEmpty(mExpressNameTV.getTag())) {

        } else {//选择了快递公司后

        }
        AppHttp.getInstance().getSelfFormPrePayMoney(city, cacheReceiver.getProvince(), cacheReceiver.getWeight());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 选择收件人
            case R.id.self_receiver_layout:
                UMeng.click(getContext(), "self_receiver_click");
                Intent intent = new Intent();
                intent.setClass(getContext(), ReceiverTabFragmentActivity.class);
                startActivityForResult(intent, 101);
                break;
            // 选择寄件人
            // case R.id.self_send_info_layout:
            case R.id.self_send_info_layout: // 选择寄件人
                intent = new Intent();
                intent.putExtra("type", 1);
                intent.setClass(getContext(), ReceiverTabFragmentActivity.class);
                startActivityForResult(intent, 103);
                break;
            // 最下面抽屉
            case R.id.self_drawer_button_layout:
                ViewGroup drawerLayout = (ViewGroup) findViewById(R.id.self_drawer_content_layout);
                int height = (findViewById(R.id.self_receiver_layout).getHeight() * 2) + Utils.dpToPx(10, getResources());
                // 如果是寄件人
                if (drawerLayout.getVisibility() == View.VISIBLE) {
                    mReceiverDown.setText("填写更多信息");
                    Drawable drawableRight = getResources().getDrawable(R.drawable.drawer_down);
                    mReceiverDown.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null);
                    mReceiverDown.setCompoundDrawablePadding(Utils.dpToPx(5, getResources()));
                    //                    mReceiverDown.setImageDrawable(getResources().getDrawable(R.drawable.drawer_down));
                    Animator.scaleY(drawerLayout, null, height, 0);
                } else {
                    drawerLayout.setVisibility(View.VISIBLE);
                    mReceiverDown.setText("点击收起");
                    Drawable drawableRight = getResources().getDrawable(R.drawable.drawer_up);
                    mReceiverDown.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null);
                    mReceiverDown.setCompoundDrawablePadding(Utils.dpToPx(5, getResources()));
                    //                    mReceiverDown.setImageDrawable(getResources().getDrawable(R.drawable.drawer_up));
                    Animator.scaleY(drawerLayout, new Callback() {
                        @Override
                        public void execute(Object... result) {
                            ScrollView scrollView = (ScrollView) findViewById(R.id.scrollview);
                            scrollView.scrollTo(0, scrollView.getBottom());
                        }
                    }, 0, height);
                }
                break;
            // 选择物品类型
            case R.id.self_goods_layout:
                DialogMgr.showGoodsType(SelfFormInfoActivity.this, findViewById(R.id.self_next_action), mGoodsType.getText().toString());
                break;
            //选择快递公司
            case R.id.self_expresscompany_layout:
                if (mExpressCompanyList != null && mExpressCompanyList.size() > 1) {
                    intent = new Intent();
                    intent.setClass(getContext(), SelfExpressCompanyActivity.class);
                    intent.putExtra("items", mExpressCompanyList);
                    startActivityForResult(intent, 105);
                }
                break;
            // 给包裹拍照
            case R.id.self_goods_image:
                UMeng.click(getContext(), "self_select_click");
                intent = new Intent();
                intent.setClass(getContext(), ReceiverCameraActivity.class);
                intent.putExtra("type", "0");
                startActivityForResult(intent, 102);
                break;
            // 添加备注
            case R.id.self_receiver_remark_layout:
                intent = new Intent();
                intent.setClass(getContext(), SelfRemarkActivity.class);
                intent.putExtra("remark", remark);
                startActivityForResult(intent, 104);
                break;
            //选填袋子编号
            case R.id.choose_bag_TV:
            case R.id.choose_bagcode_ll:
                UMeng.click(getContext(), "self_bag_scan_click");
                intent = new Intent();
                intent.setClass(getContext(), AppCaptureActivity.class);
                startActivityForResult(intent, Const.RequestCode.scan_bag);
                break;
            // 选择智能柜
            case R.id.self_next_action:
            case R.id.self_next_action1://popwin中的提交
                if (isEmpty(mReceiverInfo.getTag()) || isEmpty(cacheReceiver.getName())
                        || isEmpty(cacheReceiver.getPhone()) || isEmpty(cacheReceiver.getAddress())
                        || isEmpty(cacheReceiver.getProvince())) {
                    // mReceiverInfo.setError("填写收件人信息");
                    showToast("填写收件人信息");
                    return;
                }
                if (isEmpty(mSenderInfo.getTag()) || cacheReceiver.getSender() == null || isEmpty(cacheReceiver.getSender().getName())
                        || isEmpty(cacheReceiver.getSender().getPhone()) || isEmpty(cacheReceiver.getSender().getAddress())
                        || isEmpty(cacheReceiver.getSender().getProvince())) {
                    // mReceiverInfo.setError("填写收件人信息");
                    showToast("填写寄件人信息");
                    return;
                }
                if (isEmpty(cacheReceiver.getGoodsImage())) {
                    // showToast("请给物品拍照");
                    return;
                }
                if (isEmpty(mGoodsType.getText())) {
                    // mGoodsType.setError("填选择物品类型");
                    // showToast("填选择物品类型");
                    return;
                }
                if (mExpressCompanyList != null && mExpressCompanyList.size() > 0) {
                    if (isEmpty(cacheReceiver.getExpressCompanyId()) || isEmpty(cacheReceiver.getExpressCompanyName())) {
                        showToast("请选择快递公司");
                        return;
                    }
                }
                if (AppCache.getUser() == null) {
                    startActivity(new Intent(getContext(), LoginActivity.class));
                    return;
                }
                UMeng.click(getContext(), "selfgo_servicePoint_click");
//                intent = new Intent();
//                intent.setClass(getContext(), SelfServicePointActivity.class);
//                intent.putExtra("goodsType", cacheReceiver.getServicePoint().getGoodsType());
//                startActivityForResult(intent, 102);
                intent = new Intent();
                intent.setClass(getContext(), VisitHomeActivity.class);
                startActivity(intent);
                if (popwin != null) {
                    popwin.dismiss();
                }
                break;
            //打开或关闭popwin
            case R.id.open_or_close_pop_iv:
                if (prePriceBean != null) {
                    showChoosePop();
                }
                break;
            //价格规则
            case R.id.price_order_tv:
                intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra("title", "价格说明");
                startActivity(intent);
                break;
            //联系客服
            case R.id.courier_location_tv:
                intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:400-617-1949"));
                startActivity(intent);
                break;
            //重新定位
            case R.id.courier_new_location_tv:
                location();
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 选择收件人 - 回调
        if (requestCode == 101 && resultCode == RESULT_OK) {
            String result = cacheReceiver.getName();
            // 注意先设置tag -- 因为setText以后会触发TextWatcher
            if (isNotEmpty(result)) {
                mReceiverInfo.setTag(Str.filter(result));
                mReceiverInfo.setError(null);
                mReceiverInfo.setText("收件人: " + Str.filter(result) + " " + cacheReceiver.getPhone());
            } else {
                mReceiverInfo.setTag(null);
                mReceiverInfo.setText("收件人: ");
                mReceiverInfo.setError(null);
            }
        }
        // 拍照 -- 回调
        else if (requestCode == 102 && resultCode == RESULT_OK) {
            String capturePath = data.getStringExtra("file");
            // cache
            cacheReceiver.setGoodsImage(capturePath);
            setGoodsImage(capturePath);
            DialogMgr.showGoodsType(SelfFormInfoActivity.this, findViewById(R.id.self_next_action), mGoodsType.getText().toString());
            //
            mGoodsImage.setTag("");// set not null
            watcher.afterTextChanged(null);
        }// 选择寄件人 - 回调
        else if (requestCode == 103 && resultCode == RESULT_OK) {
            SenderBean sender = cacheReceiver.getSender();
            if (sender != null) {
                String result = sender.getName();
                if (isNotEmpty(result)) {
                    mSenderInfo.setTag(Str.filter(result));
                    mSenderInfo.setText("寄件人: " + Str.filter(result) + " " + sender.getPhone());
                    mSenderInfo.setError(null);
                    prePriceFunction();
                }
            }
        } // 添加备注-回调
        else if (requestCode == 104 && resultCode == RESULT_OK) {
            remark = data.getStringExtra("remark");
            setRemarkText(remark);
        } else if (requestCode == 105 && resultCode == RESULT_OK) {
            String expressCompanyId = cacheReceiver.getExpressCompanyId();
            String expressCompanyName = cacheReceiver.getExpressCompanyName();
            if (isNotEmpty(expressCompanyId) && isNotEmpty(expressCompanyName)) {
                mExpressNameTV.setTextColor(getResources().getColor(R.color.app_fontcolor_333333));
                mExpressNameTV.setTag(expressCompanyName);
                mExpressNameTV.setText(expressCompanyName);
            } else {
                mExpressNameTV.setTextColor(getResources().getColor(R.color.app_font_2));
                mExpressNameTV.setTag(null);
                mExpressNameTV.setText("必填");
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void setGoodsImage(String capturePath) {
        Bitmap image = BitmapUtils.loadBitmapFromLocal(capturePath);
        if (image != null) {
            mGoodsImage.setImageBitmap(image);
        }
        // 拍照回调后隐藏文字，自动弹出选择物品类型
        findViewById(R.id.self_goods_above).setVisibility(View.GONE);
        // 抽屉按钮
        findViewById(R.id.self_drawer_button_layout).setVisibility(View.VISIBLE);
        //选择快递公司和物品信息
        findViewById(R.id.self_goods_expresscompany_layout).setVisibility(View.VISIBLE);
        mAddSender.setVisibility(View.VISIBLE);
//        // 物品类型
//        findViewById(R.id.self_goods_layout).setVisibility(View.VISIBLE);
//        //选择快递公司
//        mExpressCompanyLayout.setVisibility(View.VISIBLE);
        // 寄件人、收件人
        findViewById(R.id.self_drawer_content_layout).setVisibility(View.GONE);
    }

    private void setRemarkText(String remark) {
        if (isEmpty(remark)) {
            mRemark.setText("备注: ");
            mRemarkState.setText("选填");
            cacheReceiver.setRemark("");
        } else {
            mRemarkState.setText("");
            mRemark.setText("备注: " + Str.filterEditText(remark));
            cacheReceiver.setRemark(Str.filterEditText(remark));
        }
    }

    /**
     * 选择物品类型、回调
     *
     * @param goodsType
     */
    public void onGoodsTypeSelect(CharSequence goodsType, String goodsWeight) {
        if (cacheReceiver.getServicePoint() == null) {
            ServicePointBean item = new ServicePointBean();
            item.setGoodsType(goodsType + "");
            cacheReceiver.setServicePoint(item);
            cacheReceiver.setWeight(goodsWeight);
        } else {
            cacheReceiver.getServicePoint().setGoodsType(goodsType + "");
            cacheReceiver.setWeight(goodsWeight);
        }
        mGoodsType.setText(goodsType + " " + goodsWeight + "kg");
        mGoodsType.setError(null);
    }

    @Override
    public boolean handleMessage(final Message msg) {
        switch (msg.what) {
            //定位回调方法
            case MsgID.self_baidu_location:
                bdLocation = (BDLocation) msg.obj;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (bdLocation != null && isNotEmpty(bdLocation.getProvince()) && isNotEmpty(bdLocation.getCity())) {
                            showLoadingDialog("查询中");
                            if (AppConfig.isOtherCity != 0) {
                                AppHttp.getInstance().getSelfExpressCompany(AppConfig.getProvince(), AppConfig.getCityName(), AppConfig.getDistrict(), bdLocation.getLongitude(), bdLocation.getLatitude());
                                AppHttp.getInstance().getCourierState(bdLocation.getLongitude(), bdLocation.getLatitude(), AppConfig.getCityName(), AppConfig.getProvince(), AppConfig.getDistrict());
                            } else {
                                AppHttp.getInstance().getSelfExpressCompany(bdLocation.getProvince(), bdLocation.getCity(), bdLocation.getDistrict(), bdLocation.getLongitude(), bdLocation.getLatitude());
                                AppHttp.getInstance().getCourierState(bdLocation.getLongitude(), bdLocation.getLatitude(), bdLocation.getCity(), bdLocation.getProvince(), bdLocation.getDistrict());
                            }
                        } else {
                            mCourierLocationTV.setText("定位失败");
                            DialogMgr.getNotLocation(getContext());
                            cancelLoadingDialog();
                        }
                    }
                });
                return true;
            //快递公司返回对象
            case MsgID.self_express_company:
                cancelLoadingDialog();
                final AppResult<ExpressCompanyBean> expressCompanyBeanAppResult = JSON.parseList(msg.obj, ExpressCompanyBean.class);
                if (expressCompanyBeanAppResult.isSuccess()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mExpressCompanyList = expressCompanyBeanAppResult.getResultList();
                            if (mExpressCompanyList != null && mExpressCompanyList.size() > 0) {
                                //只有一个快递公司进行隐藏并且选中，大于1个快递公司进行选择
                                if (mExpressCompanyList.size() == 1) {
                                    mExpressCompanyLayout.setVisibility(View.GONE);
                                    cacheReceiver.setExpressCompanyId(mExpressCompanyList.get(0).getId());
                                    cacheReceiver.setExpressCompanyName(mExpressCompanyList.get(0).getName());
                                    mExpressNameTV.setTag(cacheReceiver.getExpressCompanyName());
                                    mExpressNameTV.setTextColor(getResources().getColor(R.color.app_fontcolor_333333));
                                    mExpressNameTV.setText(cacheReceiver.getExpressCompanyName());
                                    mExpressNameTV.setTag(cacheReceiver.getExpressCompanyName());
                                } else {
                                    cacheReceiver.setExpressCompanyId(null);
                                    cacheReceiver.setExpressCompanyName(null);
                                    mExpressCompanyLayout.setVisibility(View.VISIBLE);
                                    mExpressNameTV.setTextColor(getResources().getColor(R.color.app_font_2));
                                    mExpressNameTV.setTag(null);
                                    mExpressNameTV.setText("必填");
                                }
                            } else {
                                cacheReceiver.setExpressCompanyId(null);
                                cacheReceiver.setExpressCompanyName(null);
                                //没有快递公司
                                mExpressCompanyLayout.setVisibility(View.GONE);
                                mExpressNameTV.setTag(null);
                                mExpressNameTV.setTextColor(getResources().getColor(R.color.app_font_2));
                                mExpressNameTV.setText("必填");
                            }
                        }
                    });
                } else {
                    showToast(expressCompanyBeanAppResult.getMessage());
                }
                return true;
            //获取检测袋子编号是否可用
            case MsgID.self_bagcode_check:
                if (isResume) {
                    cancelLoadingDialog();
                    final AppResult<BagBean> result = JSON.parser(msg.obj, BagBean.class);
                    if (result.isSuccess() && result.getResult() != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (isNotEmpty(result.getResult().getCode())) {
                                    cacheBagBean = result.getResult();
                                    cacheReceiver.setBag(cacheBagBean);
                                    mBagCode.setText("投递编号：" + Str.strFormatByEmpty(result.getResult().getCode(), true, 2, 3));
                                    mBagName.setText(result.getResult().getName());
                                    mChooseBagTV.setText("");
                                } else {
                                    mBagCode.setText("投递编号");
                                    mBagName.setText("可通过火箭投递袋、面单获得");
                                    mChooseBagTV.setText("选填");
                                }
                            }
                        });
                    } else {
                        showToast(result.getMessage());
                    }
                }
                return false;
            //在手动输入袋子编号后发送过来的信息
            case MsgID.send_bag_info:
                cacheBagBean = (BagBean) msg.obj;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isNotEmpty(cacheBagBean.getCode())) {
                            cacheReceiver.setBag(cacheBagBean);
                            mBagCode.setText("投递编号：" + Str.strFormatByEmpty(cacheBagBean.getCode(), true, 2, 3));
                            mBagName.setText(cacheBagBean.getName());
                            mChooseBagTV.setText("");
                        } else {
                            mBagCode.setText("投递编号");
                            mBagName.setText("可通过火箭投递袋、面单获得");
                            mChooseBagTV.setText("选填");
                        }
                    }
                });
                return true;
            //获取预支付的金额
            case MsgID.get_self_form_prepay_money:
                cancelLoadingDialog();
                final AppResult<SelfPrePriceBean> result = JSON.parser(msg.obj, SelfPrePriceBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result.isSuccess()) {
                            prePriceBean = result.getResult();
                            if (prePriceBean != null) {
                                mPreLayout.setVisibility(View.VISIBLE);
                                mPrePayStampTV.setVisibility(View.GONE);
                                if (prePriceBean.getCoupon() == 0) {
                                    mPrePayMoneyTV.setText(Html.fromHtml(MessageFormat.format(prePayStr, prePriceBean.getCostStr())));
                                } else {
                                    if (cacheReceiver != null && isNotEmpty(cacheReceiver.getWeight()) && Float.valueOf(cacheReceiver.getWeight()) > 3.0f) {
                                        mPrePayMoneyTV.setText(Html.fromHtml(MessageFormat.format(prePayStr, prePriceBean.getCostStr())));
                                    } else {
                                        mPrePayStampTV.setVisibility(View.VISIBLE);
                                        mPrePayMoneyTV.setText(Html.fromHtml(MessageFormat.format(prePayStr, prePriceBean.getCostStr())));
                                        mPrePayStampTV.setText(Html.fromHtml(MessageFormat.format(stampTipStr, prePriceBean.getCouponStr())));
                                    }
                                }
//                                setButtonEnableStyle(mSubmit, true);
                                if (courierResultItem == null || courierResultItem.getOpenFlag() == 0 || courierResultItem.getCourierCnt() < 1) {
                                    setLinearLayoutEnableStyle(mSubmit, false);
                                } else {
                                    setLinearLayoutEnableStyle(mSubmit, true);
                                }
                            } else {
//                                setButtonEnableStyle(mSubmit, false);
                                setLinearLayoutEnableStyle(mSubmit, false);
                            }
                        } else {
                            showToast(result.getMessage());
//                            setButtonEnableStyle(mSubmit, false);
                            setLinearLayoutEnableStyle(mSubmit, false);
                        }
                    }
                });
                return true;
            //周围有无火箭侠
            case MsgID.get_courier_state:
                cancelLoadingDialog();
                final AppResult<VisitGetCourierStateBean> courierResult = JSON.parser(msg.obj, VisitGetCourierStateBean.class);
                if (courierResult.isSuccess()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            courierResultItem = courierResult.getResult();
                            if (courierResultItem != null) {
                                if (courierResultItem.getOpenFlag() == 0) {
                                    mCourierLocationTV.setText("您当前" + bdLocation.getDistrict() + "，该地区暂无服务");
                                    mCourierLocationTV.setEnabled(false);
                                    mCourierNewLocationBtn.setVisibility(View.VISIBLE);
                                    setLinearLayoutEnableStyle(mSubmit, false);
                                } else {
                                    if (courierResultItem.getCourierCnt() > 0) {
                                        mCourierLocationTV.setText(Html.fromHtml((MessageFormat.format(centerNumStr, courierResultItem.getCourierCnt()))));
                                        mCourierLocationTV.setEnabled(false);
                                        setLinearLayoutEnableStyle(mSubmit, true);
                                    } else {
                                        mCourierLocationTV.setText(Html.fromHtml(callCenterStr));
                                        mCourierLocationTV.setEnabled(true);
                                        setLinearLayoutEnableStyle(mSubmit, false);
                                    }
                                    mCourierNewLocationBtn.setVisibility(View.GONE);

                                }

                            }
                        }
                    });
                } else {
                    showToast(courierResult.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    /**
     * 展示底部弹出的dialog
     */
    private void showChoosePop() {
        final View layout = LayoutInflater.from(this).inflate(R.layout.self_money_detail_pop, null);
        popwin = DialogMgr.createPopupWindow(this, layout);
        popwin.showAtLocation(mBottomLayout, Gravity.RIGHT | Gravity.BOTTOM, 0, 0);
        View overWeightLayout = layout.findViewById(R.id.over_weight_layout);
        layout.findViewById(R.id.open_or_close_pop_iv).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popwin != null) {
                    popwin.dismiss();
                    popwin = null;
                }
            }
        });
        layout.findViewById(R.id.price_order_tv).setOnClickListener(this);
        if (cacheReceiver != null) {
            if (isNotEmpty(cacheReceiver.getWeight()) && Float.valueOf(cacheReceiver.getWeight()) > 3.0f) {
                overWeightLayout.setVisibility(View.VISIBLE);
                String overWeightStr = "超重" + Str.roundByScale(Math.ceil(Double.valueOf(cacheReceiver.getWeight())) - 3, 0) + "公斤";
                ((TextView) layout.findViewById(R.id.overweight_desc_tv)).setText(setSpannableStr(overWeightStr + "（续重" + prePriceBean.getFlowPriceStr() + "元/公斤）", overWeightStr.length()));
                ((TextView) layout.findViewById(R.id.overwight_price_tv)).setText(Str.roundByScale(MathUtils.mul(prePriceBean.getFlowPrice(), Double.valueOf(cacheReceiver.getWeight()) - 3), 1) + "元");
            } else {
                overWeightLayout.setVisibility(View.GONE);
            }
            SenderBean senderBean = cacheReceiver.getSender();
            String address = "";
            if (senderBean == null || isEmpty(senderBean.getCity())) {
                if (isEmpty(AppCache.getCurrentCityName())) {
                    AppCache.setCurrentCityName("北京市");
                    address = "北京市" + "-" + cacheReceiver.getProvince();
                } else {
                    address = AppCache.getCurrentCityName() + "-" + cacheReceiver.getProvince();
                }
            } else {
                address = senderBean.getCity() + "-" + cacheReceiver.getProvince();
            }
            TextView normalInfoTV = (TextView) layout.findViewById(R.id.self_info_tv);
            TextView basePrice = (TextView) layout.findViewById(R.id.base_price_tv);
            normalInfoTV.setText(setSpannableStr(address + "(3公斤以内）", address.length()));
            basePrice.setText(prePriceBean.getSimplePriceStr() + "元");
            TextView prePayMoneyTV = (TextView) layout.findViewById(R.id.pre_pay_money_tv);
            TextView prePayStampTV = (TextView) layout.findViewById(R.id.pre_pay_stamp_tv);
            layout.findViewById(R.id.self_next_action1).setOnClickListener(this);
            prePayStampTV.setVisibility(View.GONE);
            if (isEmpty(prePriceBean.getCoupon())) {
                prePayMoneyTV.setText(Html.fromHtml(MessageFormat.format(prePayStr, prePriceBean.getCostStr())));
            } else {
                if (cacheReceiver != null && isNotEmpty(cacheReceiver.getWeight()) && Float.valueOf(cacheReceiver.getWeight()) > 3.0f) {
                    prePayMoneyTV.setText(Html.fromHtml(MessageFormat.format(prePayStr, prePriceBean.getCostStr())));
                } else {
                    prePayStampTV.setVisibility(View.VISIBLE);
                    prePayMoneyTV.setText(Html.fromHtml(MessageFormat.format(prePayStr, prePriceBean.getCostStr())));
                    prePayStampTV.setText(Html.fromHtml(MessageFormat.format(stampTipStr, prePriceBean.getCouponStr())));
                }
            }
        }

    }

    private SpannableString setSpannableStr(String content, int start) {
        SpannableString spannableString = new SpannableString(content);
        AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(15, true);
        AbsoluteSizeSpan sizeSpan1 = new AbsoluteSizeSpan(13, true);
        spannableString.setSpan(sizeSpan, 0, start, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        spannableString.setSpan(sizeSpan1, start + 1, content.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        return spannableString;
    }

    public void setLinearLayoutEnableStyle(LinearLayout layout, boolean enable) {
        int bottom = layout.getPaddingBottom();
        int top = layout.getPaddingTop();
        int right = layout.getPaddingRight();
        int left = layout.getPaddingLeft();
        TextView tv1 = (TextView) findViewById(R.id.tv1);
        TextView tv2 = (TextView) findViewById(R.id.tv2);
        if (enable) {
            layout.setBackgroundResource(R.drawable.app_button_selector);
            tv1.setTextColor(getResources().getColorStateList(R.color.app_buttoncolor_selector));
            tv2.setTextColor(getResources().getColorStateList(R.color.app_buttoncolor_selector));
            layout.setOnClickListener(this);
        } else {
            layout.setBackgroundResource(R.drawable.app_button_bg_disable);
            tv1.setTextColor(getResources().getColor(R.color.white));
            tv2.setTextColor(getResources().getColor(R.color.white));
            layout.setOnClickListener(null);
        }
        layout.setPadding(left, top, right, bottom);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 记录缓存
        AppCache.setParcelNew(cacheReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
